<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板</title>
    <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
    <link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">
    <script>
        // 添加脚本加载检查
        console.log('页面开始加载...');
    </script>
</head>
<body class="bg-gray-50">
    <!-- 留言板组件 -->
    <div id="messageSection" class="content-section container mx-auto px-4 py-8">
        <!-- 发表留言区域 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
            <h2 class="text-xl font-bold mb-4">发表留言</h2>
            <form id="messageForm" class="space-y-4">
                <div>
                    <textarea id="messageContent" name="content" rows="4" 
                        class="w-full p-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
                        placeholder="写下你的想法..."></textarea>
                </div>
                <div>
                    <input type="file" 
                        class="filepond" 
                        name="images"
                        id="pond"
                        multiple 
                        data-allow-multiple="true" 
                        data-max-files="5"
                        accept="image/*"/>
                </div>
                <div class="text-right">
                    <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition duration-300">
                        发表留言
                    </button>
                </div>
            </form>
        </div>

        <!-- 排序选项 -->
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold">全部留言</h2>
            <div class="flex space-x-4">
                <button id="sortByTime" class="px-4 py-2 rounded-lg transition duration-300" 
                    data-sort="time">按时间排序</button>
                <button id="sortByLikes" class="px-4 py-2 rounded-lg transition duration-300" 
                    data-sort="likes">按点赞排序</button>
            </div>
        </div>

        <!-- 留言列表 -->
        <div id="messageList" class="space-y-6"></div>

        <!-- 留言卡片模板 -->
        <template id="messageTemplate">
            <div class="message-card bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-start space-x-4">
                    <img class="user-avatar w-12 h-12 rounded-full" src="" alt="用户头像">
                    <div class="flex-1">
                        <div class="flex justify-between items-start">
                            <div>
                                <h3 class="user-name font-bold"></h3>
                                <p class="created-time text-gray-500 text-sm"></p>
                            </div>
                            <div class="flex items-center space-x-2">
                                <button class="like-btn flex items-center space-x-1 text-gray-500 hover:text-green-600">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                                            d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z">
                                        </path>
                                    </svg>
                                    <span class="like-count">0</span>
                                </button>
                            </div>
                        </div>
                        <p class="message-content mt-2 text-gray-700"></p>
                        
                        <!-- 图片展示区 -->
                        <div class="image-gallery grid grid-cols-2 gap-2 mt-4"></div>
                        
                        <!-- 评论区 -->
                        <div class="mt-4 space-y-4">
                            <div class="flex items-center space-x-2">
                                <button class="comment-btn text-gray-500 hover:text-green-600 text-sm">
                                    回复
                                </button>
                            </div>
                            <div class="comment-form hidden">
                                <textarea class="w-full p-2 border rounded-lg text-sm" rows="2" placeholder="写下你的回复..."></textarea>
                                <div class="text-right mt-2">
                                    <button class="submit-comment bg-green-600 text-white px-4 py-1 rounded-lg text-sm hover:bg-green-700">
                                        发表回复
                                    </button>
                                </div>
                            </div>
                            <div class="comments-list pl-8 space-y-3"></div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <!-- 确保 FilePond 相关脚本按正确顺序加载 -->
    <script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script>
    <script src="https://unpkg.com/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.js"></script>
    <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
    
    <script>
        // 检查 FilePond 是否已加载
        console.log('检查 FilePond 是否已加载:', typeof FilePond !== 'undefined' ? '已加载' : '未加载');
        
        // 等待 DOM 加载完成
        document.addEventListener('DOMContentLoaded', () => {
            console.log('DOM 已加载完成');
            
            try {
                // 注册 FilePond 插件
                console.log('开始注册 FilePond 插件...');
                FilePond.registerPlugin(FilePondPluginImagePreview);
                FilePond.registerPlugin(FilePondPluginFileValidateType);
                console.log('FilePond 插件注册完成');
                
                // 获取文件输入元素
                const inputElement = document.querySelector('#pond');
                console.log('文件输入元素:', inputElement);
                
                if (!inputElement) {
                    throw new Error('未找到文件输入元素');
                }
                
                // 初始化 FilePond
                const pond = FilePond.create(inputElement, {
                    name: 'file',
                    server: {
                        process: {
                            url: '/api/upload_image',
                            method: 'POST',
                            withCredentials: true,
                            headers: {
                                'Accept': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            ondata: (formData) => {
                                console.log('开始上传文件...');
                                return formData;
                            },
                            onload: response => {
                                console.log('收到上传响应:', response);
                                try {
                                    const data = JSON.parse(response);
                                    console.log('解析后的响应:', data);
                                    if (data.success && data.data && data.data.url) {
                                        console.log('上传成功，URL:', data.data.url);
                                        return data.data.url; // 返回URL作为serverId
                                    } else {
                                        const errorMsg = data.message || '未知错误';
                                        console.error('上传失败:', errorMsg);
                                        return null;
                                    }
                                } catch (error) {
                                    console.error('解析响应出错:', error);
                                    return null;
                                }
                            },
                            onerror: response => {
                                console.error('上传错误:', response);
                                const errorMsg = response.message || '上传失败';
                                console.error('错误详情:', errorMsg);
                                return errorMsg;
                            }
                        }
                    },
                    labelIdle: '拖拽图片或点击上传',
                    labelFileProcessing: '上传中',
                    labelFileProcessingComplete: '上传完成',
                    labelFileProcessingAborted: '上传取消',
                    labelFileProcessingError: '上传失败',
                    labelFileRemoveError: '移除失败',
                    labelTapToCancel: '点击取消',
                    labelTapToRetry: '点击重试',
                    labelTapToUndo: '点击撤销',
                    allowMultiple: true,
                    maxFiles: 5,
                    acceptedFileTypes: ['image/jpeg', 'image/png', 'image/gif'],
                    fileValidateTypeDetectType: (source, type) => new Promise((resolve, reject) => {
                        resolve(type);
                    }),
                    instantUpload: true,
                    allowRevert: false,
                    chunkUploads: false,
                    allowProcess: true
                });
                
                console.log('FilePond 初始化完成');
                
                // 存储上传成功的图片URL
                const uploadedImages = new Map();

                // 添加文件添加事件监听
                pond.on('addfile', (error, file) => {
                    if (error) {
                        console.error('添加文件错误:', error);
                        return;
                    }
                    console.log('文件已添加:', file.filename);
                });
                
                // 添加上传完成事件监听
                pond.on('processfile', (error, file) => {
                    if (error) {
                        console.error('文件处理错误:', error);
                        return;
                    }
                    console.log('文件处理成功, serverId:', file.serverId);
                    if (file.serverId) {
                        uploadedImages.set(file.id, file.serverId);
                        console.log('已存储图片URL:', file.serverId);
                        console.log('当前所有图片URLs:', Array.from(uploadedImages.values()));
                    }
                });

                // 添加文件移除事件监听
                pond.on('removefile', (error, file) => {
                    if (error) {
                        console.error('文件移除错误:', error);
                        return;
                    }
                    console.log('文件已移除:', file.filename);
                    uploadedImages.delete(file.id);
                    console.log('当前所有图片URLs:', Array.from(uploadedImages.values()));
                });
                
                // 处理表单提交
                document.getElementById('messageForm').onsubmit = async (e) => {
                    e.preventDefault();
                    const content = document.getElementById('messageContent').value.trim();
                    
                    if (!content) {
                        alert('请输入留言内容');
                        return;
                    }

                    try {
                        // 获取所有已上传的图片URL
                        const images = Array.from(uploadedImages.values());
                        console.log('提交留言，图片URLs:', images);
                        
                        const response = await fetch('/api/message/create', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({ content, images })
                        });
                        
                        const result = await response.json();
                        console.log('留言创建响应:', result);
                        
                        if (result.code === 200) {
                            // 清空表单和图片
                            document.getElementById('messageContent').value = '';
                            pond.removeFiles();
                            uploadedImages.clear();
                            loadMessages(currentSort);
                        } else {
                            alert(result.msg || '发表失败');
                        }
                    } catch (error) {
                        console.error('发表留言错误:', error);
                        alert('发表失败，请重试');
                    }
                };
                
            } catch (error) {
                console.error('FilePond 初始化错误:', error);
            }
            
            // 初始化加载留言列表
            loadMessages('time');
            document.querySelector('[data-sort="time"]').classList.add('bg-green-600', 'text-white');
        });

        // 当前排序方式
        let currentSort = 'time';

        // 加载留言列表
        function loadMessages(sortBy = 'time') {
            fetch(`/api/message?sort=${sortBy}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const messageList = document.getElementById('messageList');
                        messageList.innerHTML = '';
                        result.data.forEach(message => {
                            const messageElement = renderMessage(message);
                            messageList.appendChild(messageElement);
                        });
                    } else {
                        alert(result.msg || '加载失败');
                    }
                })
                .catch(error => console.error('Error loading messages:', error));
        }

        // 渲染单条留言
        function renderMessage(message) {
            const template = document.getElementById('messageTemplate');
            const clone = template.content.cloneNode(true);
            const messageCard = clone.querySelector('.message-card');
            
            // Set message card ID
            messageCard.id = `message-${message.id}`;
            
            // 设置基本信息
            messageCard.querySelector('.user-avatar').src = message.avatar || '/static/images/default-avatar.png';
            messageCard.querySelector('.user-name').textContent = message.nickname || message.username;
            messageCard.querySelector('.created-time').textContent = message.created_time;
            messageCard.querySelector('.message-content').textContent = message.content;
            
            // Set like button state and count
            const likeBtn = messageCard.querySelector('.like-btn');
            if (message.is_liked) {
                likeBtn.classList.add('text-green-600');
            }
            messageCard.querySelector('.like-count').textContent = message.like_count;
            
            // 渲染图片
            const gallery = messageCard.querySelector('.image-gallery');
            if (message.images && message.images.length > 0) {
                gallery.style.display = 'grid';
                message.images.forEach(url => {
                    const img = document.createElement('img');
                    // 提取基础URL，移除所有查询参数
                    const baseUrl = url.split('?')[0];
                    // 解码URL以处理可能的编码字符
                    img.src = decodeURIComponent(baseUrl);
                    img.className = 'w-full h-48 object-cover rounded-lg cursor-pointer';
                    img.onclick = () => window.open(img.src, '_blank');
                    gallery.appendChild(img);
                });
            } else {
                gallery.style.display = 'none';
            }
            
            // 渲染评论
            const commentsList = messageCard.querySelector('.comments-list');
            if (message.comments && message.comments.length > 0) {
                message.comments.forEach(comment => {
                    const commentElement = renderComment(comment, message.id);
                    commentsList.appendChild(commentElement);
                });
            }
            
            // 添加事件监听器
            messageCard.querySelector('.like-btn').onclick = () => toggleLike(message.id);
            const commentBtn = messageCard.querySelector('.comment-btn');
            const commentForm = messageCard.querySelector('.comment-form');
            
            commentBtn.onclick = () => {
                commentForm.classList.toggle('hidden');
                if (!commentForm.classList.contains('hidden')) {
                    commentForm.querySelector('textarea').focus();
                }
            };
            
            const submitCommentBtn = messageCard.querySelector('.submit-comment');
            submitCommentBtn.onclick = () => {
                const content = commentForm.querySelector('textarea').value;
                submitComment(message.id, null, content);
            };
            
            return messageCard;
        }

        // 渲染评论
        function renderComment(comment, messageId) {
            const div = document.createElement('div');
            div.className = 'bg-gray-50 rounded p-3 mb-3';
            div.innerHTML = `
                <div class="flex items-start space-x-2">
                    <img src="${getBaseUrl(comment.avatar)}" 
                         class="w-8 h-8 rounded-full">
                    <div class="flex-1">
                        <div class="flex justify-between">
                            <span class="font-semibold">${comment.nickname || comment.username}</span>
                            <span class="text-gray-500 text-sm">${comment.created_time}</span>
                        </div>
                        <p class="text-sm mt-1">${comment.content}</p>
                        
                        <!-- 回复按钮 -->
                        <div class="mt-2 flex items-center space-x-2">
                            <button class="reply-btn text-gray-500 hover:text-green-600 text-sm">
                                回复
                            </button>
                        </div>
                        
                        <!-- 回复表单 -->
                        <div class="reply-form hidden mt-2">
                            <textarea class="w-full p-2 border rounded-lg text-sm" rows="2" 
                                placeholder="回复 ${comment.nickname || comment.username}..."></textarea>
                            <div class="text-right mt-2">
                                <button class="submit-reply bg-green-600 text-white px-4 py-1 rounded-lg text-sm hover:bg-green-700">
                                    发表回复
                                </button>
                            </div>
                        </div>
                        
                        <!-- 回复列表 -->
                        <div class="replies-list pl-4 mt-2 space-y-2">
                            ${renderReplies(comment.replies)}
                        </div>
                    </div>
                </div>
            `;

            // 添加回复功能事件监听
            const replyBtn = div.querySelector('.reply-btn');
            const replyForm = div.querySelector('.reply-form');
            
            replyBtn.onclick = () => {
                replyForm.classList.toggle('hidden');
                if (!replyForm.classList.contains('hidden')) {
                    replyForm.querySelector('textarea').focus();
                }
            };
            
            const submitReplyBtn = div.querySelector('.submit-reply');
            submitReplyBtn.onclick = () => {
                const content = replyForm.querySelector('textarea').value;
                submitComment(messageId, comment.id, content);
            };

            return div;
        }

        // 渲染回复
        function renderReplies(replies) {
            if (!replies || replies.length === 0) return '';
            
            return replies.map(reply => `
                <div class="bg-gray-100 rounded p-2">
                    <div class="flex items-start space-x-2">
                        <img src="${getBaseUrl(reply.avatar)}" 
                             class="w-6 h-6 rounded-full">
                        <div class="flex-1">
                            <div class="flex items-baseline space-x-1">
                                <span class="font-semibold text-sm">${reply.nickname || reply.username}</span>
                                <span class="text-gray-500 text-xs">回复</span>
                                <span class="font-semibold text-sm">${reply.parent_nickname || reply.parent_username}</span>
                            </div>
                            <p class="text-sm mt-1">${reply.content}</p>
                            <div class="mt-1">
                                <span class="text-gray-500 text-xs">${reply.created_time}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 辅助函数：获取基础URL（移除查询参数）
        function getBaseUrl(url) {
            if (!url) return '/static/images/default-avatar.png';
            const baseUrl = decodeURIComponent(url.split('?')[0]);
            // 处理双重编码的情况
            return baseUrl.includes('%') ? decodeURIComponent(baseUrl) : baseUrl;
        }

        // 切换点赞状态
        function toggleLike(messageId) {
            fetch(`/api/message/${messageId}/like`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // Update like count immediately
                    const messageCard = document.querySelector(`#message-${messageId}`);
                    const likeBtn = messageCard.querySelector('.like-btn');
                    const likeCount = messageCard.querySelector('.like-count');
                    likeCount.textContent = result.data.like_count;
                    likeBtn.classList.toggle('text-green-600', result.data.is_liked);
                } else {
                    alert(result.msg || '操作失败');
                }
            })
            .catch(error => console.error('Error toggling like:', error));
        }

        // 提交评论
        function submitComment(messageId, parentId, content) {
            if (!content.trim()) {
                alert('请输入评论内容');
                return;
            }
            
            fetch(`/api/message/${messageId}/comment`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content, parent_id: parentId })
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // 重新加载消息列表以显示新评论
                    loadMessages(currentSort);
                    // 清空并隐藏评论框
                    const messageCard = document.querySelector(`#message-${messageId}`);
                    const commentForm = messageCard.querySelector('.comment-form');
                    commentForm.querySelector('textarea').value = '';
                    commentForm.classList.add('hidden');
                } else {
                    alert(result.msg || '评论失败');
                }
            })
            .catch(error => {
                console.error('Error submitting comment:', error);
                alert('评论失败，请重试');
            });
        }

        // 排序按钮事件
        document.querySelectorAll('[data-sort]').forEach(button => {
            button.onclick = (e) => {
                const sortBy = e.target.dataset.sort;
                currentSort = sortBy;
                document.querySelectorAll('[data-sort]').forEach(btn => {
                    btn.classList.remove('bg-green-600', 'text-white');
                });
                e.target.classList.add('bg-green-600', 'text-white');
                loadMessages(sortBy);
            };
        });
    </script>
</body>
</html>